import { Button, Empty, NavBar, Toast } from "antd-mobile";
import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import $fetch from "../../../utils/app/$fetch";
import $reducer from "../../../utils/app/$reducer";
import Decimal from 'decimal.js';
import "./style.scss";

const CouponType: any = {
  0: "特典券",
  1: "一般商品",
};

const GoodsCartPage = () => {
  const navigate: any = useNavigate();
  const location: any = useLocation();
  const initState: any = {
    resList: [],
    selectAllStatus: false,
    totalAmount: 0,
    selectGoods: [],
    isLoading: true,
  };

  const [state, dispatch] = $reducer({ ...initState });

  useEffect(() => {
    initPage();
  }, []);

  const initPage = async () => {
    const res: any = await $fetch("cart/list");
    if (!res?.length) {
      dispatch({ isLoading: false });
      return;
    }
    const tedianquan = res.filter((item: any) => item.goodsType === 0);
    const yiban = res.filter((item: any) => item.goodsType === 1);
    let resList = [];
    if (!!tedianquan?.length) {
      resList.push({ shopId: "tedianquan", goodsType: 0, content: tedianquan });
    }
    if (!!yiban?.length) {
      resList.push({ shopId: "yiban", goodsType: 1, content: yiban });
    }

    dispatch({ resList, isLoading: false });
  };

  const back = () => {
    window.history.go(-1);
  };

  // 处理全选
  const handleAllSelect = () => {
    const newResList = state?.resList?.map((shop: any) => {
      return {
        ...shop,
        shopStatus: !state?.selectAllStatus,
        content: shop?.content?.map((good: any) => {
          return {
            ...good,
            goodStatus: !state?.selectAllStatus,
          };
        }),
      };
    });
    dispatch({ selectAllStatus: !state?.selectAllStatus, resList: newResList });
    handleTotalAmount(newResList);
  };

  // 处理店铺全选
  const handleShopSelect = (shopId: any) => {
    const newResList = state?.resList?.map((shop: any) => {
      if (shopId === shop?.shopId) {
        return {
          ...shop,
          shopStatus: !shop?.shopStatus,
          content: shop?.content?.map((good: any) => {
            return {
              ...good,
              goodStatus: !shop?.shopStatus,
            };
          }),
        };
      }
      return shop;
    });
    const newSelectAll = newResList?.every((shop: any) => shop?.shopStatus);
    dispatch({ resList: newResList, selectAllStatus: newSelectAll });
    handleTotalAmount(newResList);
  };

  // 处理商品单个选择
  const handleGoodSelect = (shopId: any, goodsId: any) => {
    const newResList = state?.resList?.map((shop: any) => {
      if (shopId === shop?.shopId) {
        const newContentList = shop?.content?.map((good: any) => {
          if (goodsId === good?.goodsId) {
            return {
              ...good,
              goodStatus: !good?.goodStatus,
            };
          }
          return good;
        });
        const newShopStatus = newContentList?.every(
          (good: any) => good?.goodStatus
        );
        return {
          ...shop,
          shopStatus: newShopStatus,
          content: newContentList,
        };
      }
      return shop;
    });
    const newSelectAll = newResList?.every((shop: any) => shop?.shopStatus);
    dispatch({ resList: newResList, selectAllStatus: newSelectAll });
    handleTotalAmount(newResList);
  };

  // 处理商品数量增加
  const handleNumAdd = (shopId: any, goodsId: any) => {
    const newResList = state?.resList?.map((shop: any) => {
      if (shopId === shop?.shopId) {
        const newContentList = shop?.content?.map((good: any) => {
          if (goodsId === good?.goodsId) {
            $fetch(
              "cart/update/quantity",
              {
                id: good?.id,
                quantity: good?.quantity + 1,
              },
              { loading: false }
            );
            return {
              ...good,
              quantity: good?.quantity + 1,
            };
          }
          return good;
        });
        return {
          ...shop,
          content: newContentList,
        };
      }
      return shop;
    });
    dispatch({ resList: newResList });
    handleTotalAmount(newResList);
  };

  // 处理商品数量减少
  const handleNumReduce = (shopId: any, goodsId: any) => {
    let newResList = state?.resList?.map((shop: any) => {
      if (shopId === shop?.shopId) {
        let newContentList = shop?.content?.map((good: any) => {
          if (goodsId === good?.goodsId) {
            let newCount = good?.quantity - 1;
            if (newCount >= 1) {
              $fetch(
                "cart/update/quantity",
                { id: good?.id, quantity: newCount },
                { loading: false }
              );
              return { ...good, quantity: newCount };
            } else if (newCount === 0) {
              $fetch(
                `cart/delete?ids=${good?.id}`,
                { ids: [good?.id] },
                { method: "post", noGroupId: "no", loading: false }
              );
              return {};
            }
          }
          return good;
        });
        newContentList = newContentList.filter(
          (item: any) => JSON.stringify(item) !== "{}"
        );
        return {
          ...shop,
          content: newContentList,
        };
      }
      return shop;
    });
    newResList = newResList.filter((item: any) => !!item?.content?.length);
    dispatch({ resList: newResList });
    handleTotalAmount(newResList);
  };

  // 计算总价
  const handleTotalAmount = (newResList: any) => {
    let totalAmount: any = 0;
    newResList?.forEach((shop: any) => {
      shop?.content?.forEach((good: any) => {
        if (good?.goodStatus) {
          const temp = Decimal.mul(good?.quantity, good?.price);
          totalAmount = Decimal.add(totalAmount, temp)
          // totalAmount += good?.quantity * good?.price;
        }
      });
    });
    dispatch({ totalAmount });
  };

  const handleBuy = () => {
    if (!state?.totalAmount) {
      Toast.show("请至少选择一件商品！");
      return;
    }
    let goods: any = [];
    state?.resList.forEach((item: any) => {
      goods = goods.concat(...item?.content);
    });
    let cartIds: any = [];
    goods.map((item: any) => {
      if (item?.goodStatus) {
        cartIds.push(item?.id);
      }
    });

    navigate("/goods/order", { state: { cartIds } });
  };

  const renderView = () => {
    if (state?.isLoading) return null;
    if (!state?.resList?.length)
      return <Empty description="你的购物车空空如也" />;
    return (
      <>
        <ul className="that_cart_list">
          {state?.resList?.map((shop: any) => {
            if (shop?.content?.length > 0) {
              return (
                <li key={shop?.shopId} className="that_cart_item">
                  <div className="shop_select">
                    <em
                      onClick={() => handleShopSelect(shop?.shopId)}
                      className={shop?.shopStatus ? "isChecked" : ""}
                    ></em>
                    <span>{CouponType[shop?.goodsType]}</span>
                  </div>
                  {shop?.content?.map((good: any) => {
                    return (
                      <div className="good_select" key={good?.goodsId}>
                        <em
                          onClick={() => {
                            handleGoodSelect(shop?.shopId, good?.goodsId);
                          }}
                          className={good?.goodStatus ? "isChecked" : ""}
                        ></em>
                        <div className="item_right">
                          <div className="img">
                            <img src={good?.goodsPhoto} alt="" />
                          </div>
                          <div>
                            <h3>{good?.goodsName}</h3>
                            <div>
                              <div>￥{good?.price.toFixed(2)}</div>
                              <div>
                                <div
                                  className="num_down"
                                  onClick={() =>
                                    handleNumReduce(shop?.shopId, good?.goodsId)
                                  }
                                >
                                  -
                                </div>
                                <div className="item_num">{good?.quantity}</div>{" "}
                                <div
                                  className="num_add"
                                  onClick={() =>
                                    handleNumAdd(shop?.shopId, good?.goodsId)
                                  }
                                >
                                  +
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </li>
              );
            }
          })}
        </ul>
        <div className="that_footer">
          <div className='item_left'>
            <em
              onClick={handleAllSelect}
              className={state?.selectAllStatus ? "isChecked" : ""}
            ></em>
            <span>全选</span>
            <div className="total">
              合计:<span>￥</span>
              <span>{state?.totalAmount.toFixed(2)}</span>
            </div>
          </div>

          <Button onClick={() => handleBuy()}>去结算</Button>
        </div>
      </>
    );
  };

  return (
    <div className="container_goods_cart">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={back}
      >
        购物车
      </NavBar>
      {renderView()}
    </div>
  );
};

export default GoodsCartPage;
